# Create your views here.
# -*- coding: utf-8 -*-
import datetime
import time
import Image

from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect,HttpResponse
from django.utils import simplejson
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout
from django.utils.translation import ugettext_lazy as _
from forms import RegisterForm,LoginForm,UsericonForm,UserAccountForm,ChangePasswordForm
from django.http import Http404

from goplay import settings
from goplay.account.models import Message
from goplay.activity.models import Activity
from goplay.sinaweibo.getUserInfo import getUser
from goplay.activity import forms
from goplay.sinaweibo import forms as sinaform
from goplay.activity import friendActivity
from goplay.sinaweibo.models import UserInfo,Province


def index(request):
    addActivity=False
    today=datetime.datetime.now()
    #用户是否已经登录
    if request.user.is_authenticated():
        #username_email=request.user.username
        #nickname=username_email[0:username_email.find('@')]
        sinauser=request.session['userinfo']
        userFriends=UserInfo.objects.filter(username=sinauser['username']).values('friends')
        ufnames=userFriends[0].get("friends")

        latestActivity=Activity.objects.filter(username=sinauser['username']).order_by('-datetime').values('id','activityname','date','datetime')
        if not latestActivity:
            request.session['latestActivity']='no activity'
            addActivity=True
        else:
            request.session['latestActivity']=latestActivity[0]
            latestDate=latestActivity[0].get('datetime')
            days=(today-latestDate).days
            if days>5:
                addActivity=True
                
        #将字符串型的好友名字转变成列表，并得到相应的信息            
        #friendsList=strToList(ufnames,access_token.key,access_token.secret)
        #得到所有好友的活动信息
        if ufnames:
            fa=friendActivity.getFriendActivity(sinauser['city'],ufnames)
        else:
            fa=()
        nickname=sinauser['username']
    else:
        return HttpResponseRedirect(reverse('login'))       
    return render_to_response("account/welcome.html",{'nickname':nickname,'fa':fa,'addActivity':addActivity,'form':forms.AddActivityForm(),'messageform':sinaform.sendMessagesForm(),'suggestionform':forms.addSuggestionForm()},context_instance=RequestContext(request))


  
def login(request):
    template_var={}
    form=LoginForm()
    if request.method=="POST":
        form=LoginForm(request.POST.copy())
        if form.is_valid():
            if(_login(request,form.cleaned_data["email"],form.cleaned_data["password"])):                        
                return HttpResponseRedirect(reverse("index"))
            else:
                return HttpResponseRedirect(reverse("login"))
    template_var["form"]=form
    return render_to_response("account/login.html",template_var,context_instance=RequestContext(request))

def _login(request,email,password):
    ret=False
    user=authenticate(username=email,password=password)
    if user:
        if user.is_active:
            auth_login(request,user)
            nickname=User.objects.filter(username=email).values('first_name')[0].get('first_name')
            #request.session['nickname']=nickname[0].get('first_name')
            #从数据库中取出用户id,并存储在session中调用
            userinfo=UserInfo.objects.filter(username__iexact=nickname).values('id','username','province','city','profile_image')
            if not userinfo:
                request.session['userinfo']=email
            else:
                cityName=Province.objects.filter(province_id=userinfo[0].get('province'),city_id=userinfo[0].get('city'))
                if not cityName:
                    cityName=''
                else:
                    cityName=cityName[0]
                userinfo[0]['cityname']=cityName
                request.session['userinfo']=userinfo[0]        
            ret=True
        else:
            messages.add_message(request,messages.INFO,_(u'用户没有激活'))
    else:
        messages.add_message(request, messages.INFO, _(u'用户不存在'))
    return ret

    
def register(request):
    template_var={}
    form=RegisterForm()
    if request.method=="POST":
        form=RegisterForm(request.POST.copy())
        if form.is_valid():
            email=form.cleaned_data["email"]
            password=form.cleaned_data["password"]
            nickname=form.cleaned_data["nickname"]
            gender=form.cleaned_data['gender']
            province=form.cleaned_data['province']
            city=form.cleaned_data['city']
            if gender=='m':
                image=settings.MEDIA_URL+"avatar_male.png"
            else:
                image=settings.MEDIA_URL+"avatar_female.png"
            userinfo=UserInfo(username=nickname,gender=gender,province=province,city=city,profile_image=image)
            userinfo.save()
            if userinfo:
                User.objects.create_user(email,email,password)#使用邮箱代替username,实现使用邮箱注册。
                User.objects.filter(username=email).update(first_name=nickname)
            _login(request,email,password)#注册完成了以后直接登录系统
            return HttpResponseRedirect(reverse("index"))
    template_var['form']=form
    return render_to_response("account/register.html",template_var,context_instance=RequestContext(request))
    

def logout(request):
    oauth_access_token=request.session.get('oauth_access_token',None)
    if oauth_access_token:
        del request.session['oauth_access_token']
        auth_logout(request)
    else:
        auth_logout(request)
    return HttpResponseRedirect(reverse('login'))

def accountManage(request):
    userinfo=request.session['userinfo']
    user=UserInfo.objects.filter(username=userinfo['username']).values('profile_image','friends')[0]
    if request.method=='POST':
        form=UserAccountForm(request,request.POST.copy())
        if form.is_valid():
            province=form.cleaned_data['province']
            city=form.cleaned_data['city']
            UserInfo.objects.filter(username=userinfo['username']).update(province=province,city=city)
            messages.add_message(request,messages.INFO,_(u'资料修改成功'))    
    form=UserAccountForm(request)          
    return render_to_response("account/accounts.html",{'user':user,'form':form},context_instance=RequestContext(request))

def friends_manage(request):
    friends_info=[]
    friendsInfo={}
    after_range_num=10
    bevor_range_num=9
    try:
        page=int(request.GET.get("page",1))
        if page<1:
            page=1
    except ValueError:
        page=1
        
    userinfo=request.session['userinfo']
    user=UserInfo.objects.filter(username=userinfo['username']).values('friends')[0]
    if user.get('friends'):
        friends_list=user.get('friends').rsplit(',')
        friends_name_list=friends_list[0:len(friends_list):2]
        friends_image_list=friends_list[1:len(friends_list):2]
        for friend_name in friends_name_list:
                i=friends_name_list.index(friend_name)
                friendsInfo['friend_name']=friend_name
                friendsInfo['friend_image']=friends_image_list[i]
                friends_info.append(dict(friendsInfo))
                
        
    else:
        pass
    paginator=Paginator(friends_info,10)   
    try:
        pages=paginator.page(page)
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        pages=paginator.page(1)
        
    if page>=after_range_num:
        page_range=paginator.page_range[page-after_range_num+bevor_range_num]
    else:
        page_range=paginator.page_range[0:int(page)+bevor_range_num]
    return render_to_response("account/friends.html",{'user':user,"friends_info":friends_info,"pages":pages,'page_range':page_range},context_instance=RequestContext(request))  

def delFriend(request):
    friends=''
    friends_name_list=[]
    friends_image_list=[]
    user=request.session['userinfo']
    if request.method=='GET':
        GET=request.GET
        name=GET.get('fr_name')
        image=GET.get('fr_image')
        UserFriends=UserInfo.objects.filter(username=user['username']).values('friends')[0]
        if UserFriends:
            friends_list=UserFriends.get('friends').split(',')
            friends_name_list=friends_list[0:len(friends_list):2]
            friends_image_list=friends_list[1:len(friends_list):2]
            friends_name_list.remove(name)
            friends_image_list.remove(image)
            for friend_name in friends_name_list:

                i=friends_name_list.index(friend_name)
                friends=friends+','+friend_name+','+friends_image_list[i]
                result=friends[1:len(friends)]          
            UserInfo.objects.filter(username=user['username']).update(friends=result)                
        results={'success':True}
        json = simplejson.dumps(results)
        return HttpResponse(json, mimetype='application/json')
    else:
        raise Http404()
    
def user_icon(request):
    form=UsericonForm()
    if request.method=="POST":
        form=UsericonForm(request.POST,request.FILES)
        print form
        if form.is_valid():
        #if 'image' in request.FILES:
            now=time.time()
            userinfo=request.session['userinfo']
            reqfile=request.FILES['image']
            image=Image.open(reqfile)
            image.thumbnail((50,50),Image.ANTIALIAS)
            folder=settings.MEDIA_ROOT.replace('\\','/')+'/usericon'     
            #name = '%s/%s%s' %(settings.MEDIA_ROOT,now,reqfile.name) 
            name = '%s/%s%s' %(folder,now,reqfile.name) 
            
            image.save(name)
            image_url='%s%s%s' %(settings.MEDIA_URL,now,reqfile.name)
            UserInfo.objects.filter(username=userinfo['username']).update(profile_image=image_url)
            
            #User.objects.filter(username=username).update(last_login=datetime.datetime.now())
            return HttpResponseRedirect(reverse('accountManage'))
        else:
            return render_to_response("account/usericon.html",{'form':form},context_instance=RequestContext(request))
    return render_to_response("account/usericon.html",{'form':form},context_instance=RequestContext(request))    
    
    
'''修改密码'''
def change_password(request):
    userinfo=request.session['userinfo']
    form=ChangePasswordForm(userinfo['username'])
    if request.method=="POST":
        form=ChangePasswordForm(userinfo['username'],request.POST.copy())
        if form.is_valid():
            password=form.cleaned_data['new_password']
            user=User.objects.get(username=userinfo['username'])
            user.set_password(password)
            user.save()
            messages.add_message(request,messages.INFO,_(u'密码修改成功'))
    return render_to_response("account/changepassword.html",{'form':form},context_instance=RequestContext(request))


def notice(request):
    user=request.session['userinfo']
    after_range_num=10
    bevor_range_num=9
    try:
        page=int(request.GET.get("page",1))
        if page<1:
            page=1
    except ValueError:
        page=1
        
    result=Message.objects.filter(receiver_id=user['id']).values('id','sender_id','receiver_time','readed','status','title','message')
    paginator=Paginator(result,10)
    
    try:
        notices=paginator.page(page)
    except(EmptyPage,InvalidPage,PageNotAnInteger):
        notices=paginator.page(1)
    
    if page>=after_range_num:
        page_range=paginator.page_range[page-after_range_num+bevor_range_num]
    else:
        page_range=paginator.page_range[0:int(page)+bevor_range_num]
    return render_to_response('account/notice.html',{'notices':notices,'page_range':page_range},context_instance=RequestContext(request))


'''加好友'''
def add_friend(request):
    user=request.session['userinfo']
    r_id=request.GET['userid']
    m=request.GET['m']
    notice=Message.objects.filter(sender_id=user['id'],receiver_id=r_id)
    if not notice:
        message=Message(sender_id=user['id'],receiver_id=r_id,receiver_time=datetime.datetime.now(),readed=False,title=user['username']+'请求加为好友',message=m)
        message.save()
    else:
        Message.objects.filter(sender_id=user['id'],receiver_id=r_id).update(receiver_time=datetime.datetime.now(),message=m)
    return HttpResponse(simplejson.dumps('success'), mimetype='application/json')


'''接受好友请求，互相把对方加入自己的好友列表'''
def accept_friend(request):
    mid=request.GET['id']
    users=Message.objects.filter(id=mid).values('sender_id','receiver_id')
    senderId=users[0].get('sender_id')
    receiverId=users[0].get('receiver_id')
    senderInfo=UserInfo.objects.filter(id=senderId).values('username','profile_image','friends')
    receiverInfo=UserInfo.objects.filter(id=receiverId).values('username','profile_image','friends')
    if senderInfo[0].get('friends'):
        sender_friend=senderInfo[0].get('friends')+','+receiverInfo[0].get('username')+','+receiverInfo[0].get('profile_image')
    else:
        sender_friend=receiverInfo[0].get('username')+','+receiverInfo[0].get('profile_image')
        
    if receiverInfo[0].get('friends'):
        receiver_friend=receiverInfo[0].get('friends')+','+senderInfo[0].get('username')+','+senderInfo[0].get('profile_image')
    else:
        receiver_friend=senderInfo[0].get('username')+','+senderInfo[0].get('profile_image')
    
    UserInfo.objects.filter(id=senderId).update(friends=sender_friend)
    UserInfo.objects.filter(id=receiverId).update(friends=receiver_friend)
    
    
    Message.objects.filter(id=mid).update(read_time=datetime.datetime.now(),readed=True,status='accept')
    return HttpResponse(simplejson.dumps('success'), mimetype='application/json')

'''忽略好友请求，将请求标记为忽略'''
def ignore_friend(request):
    mid=request.GET['id']
    Message.objects.filter(id=mid).update(read_time=datetime.datetime.now(),readed=True,status='ignore')
    return HttpResponse(simplejson.dumps('success'), mimetype='application/json')


'''省份和城市联动，根据选择的省份动态加载城市信息'''
def city_list(request):
    city_list =[]
    province = request.GET['provinceID']
    citys = Province.objects.filter(province_id = province).values('city_id','city_name')
    for city in citys:
        c = {}
        c['label'] = city.get("city_name")
        c['text'] = city.get("city_id")
        city_list.append(c)
    return HttpResponse(simplejson.dumps(city_list), mimetype='application/json')

#将好友信息转换成list
def strToList(ufnames,token,tokenSecret):
    ufsinfo=([])
    ufnames_list=ufnames.rsplit(',')
    for ufname in ufnames_list:
        ufsinfo.append(getUser().getUserInfo(ufname, token, tokenSecret))    
    return ufsinfo

